package sk.tuke.lara.masplc.agents;

import jade.core.Agent;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;

import java.util.ArrayList;
import java.util.List;

import sk.tuke.lara.masplc.Servicies;
import sk.tuke.lara.masplc.agents.ConstraintsDTO.Operators;
import sk.tuke.lara.masplc.utils.MathUtils;

public class PlcAgent extends Agent {

    private static final long serialVersionUID = 6458138827246031534L;

    int maxVykon = MathUtils.randomInt(10, 40) * 10;
    int priority = MathUtils.randomInt(0, 10);
    List<ConstraintsDTO> constraintsList = new ArrayList<ConstraintsDTO>();

    int aktualniVykon = 0;
    private PlcAgentGui plcAgentGui;


    @Override
    protected void setup() {
        System.out.println("plc agent created " + getName() + "(priority=" + priority + ")");

        //init state
        constraintsList.add(new ConstraintsDTO(getLocalName(), Operators.XgtC, String.valueOf(MathUtils.randomInt(5, 10))));

        //init behaviour
        addBehaviour(new SetPlcRequestBehaviour(this));
        addBehaviour(new RequirementsRequestBehaviour(this));
        registerHorakyService();

        //init GUI
        plcAgentGui = new PlcAgentGui(this);
        plcAgentGui.showGui();
        changeState();
    }

    @Override
    protected void takeDown() {
        deregisterService();
        plcAgentGui.dispose();
        System.out.println("plc agent cleaned");
    }

    private void registerHorakyService() {
        // Register the book-selling service in the yellow pages
        DFAgentDescription dfd = new DFAgentDescription();
        dfd.setName(getAID());
        ServiceDescription sd = new ServiceDescription();
        sd.setType(Servicies.FIRE_CONTROL_SERVICE);
        sd.setName("Control of Horak");
        dfd.addServices(sd);
        try {
            DFService.register(this, dfd);
        } catch (FIPAException fe) {
            fe.printStackTrace();
        }
    }

    private void deregisterService() {
        try {
            DFService.deregister(this);
        } catch (FIPAException fe) {
            fe.printStackTrace();
        }
    }

    public void changeState() {
        plcAgentGui.drawState();
    }

}
